package cn.edu.hstc.wm.ui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import cn.edu.hstc.wm.AppApplication;
import cn.edu.hstc.wm.AppConfigs;
import cn.edu.hstc.wm.Constants;
import cn.edu.hstc.wm.R;
import cn.edu.hstc.wm.adapter.MainPagerAdapter;
import cn.edu.hstc.wm.adapter.SlideMenuListAdapter;
import cn.edu.hstc.wm.service.AppConfigService;
import cn.edu.hstc.wm.service.UpdateManager;
import cn.edu.hstc.wm.ui.fragment.CategoryMode;
import cn.edu.hstc.wm.ui.fragment.NetworkDisableFragment;
import cn.edu.hstc.wm.ui.fragment.StoreMode;
import cn.edu.hstc.wm.utils.IntentUtil;
import cn.edu.hstc.wm.utils.LogUtil;
import cn.edu.hstc.wm.widget.CustomToast;
import cn.edu.hstc.wm.widget.PagerSlideTab;
import cn.edu.hstc.wm.widget.PopupWindows;
import cn.edu.hstc.wm.widget.slidingmenu.SlidingFragmentActivity;
import cn.edu.hstc.wm.widget.slidingmenu.SlidingMenu;

import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.map.SupportMapFragment;

/**
 * @ClassName: MainActivity
 * @Description: 主界面,初始化完成后进入该主界面
 * 
 * @ModificationHistory
 */
public class MainActivity extends SlidingFragmentActivity implements View.OnClickListener, OnPageChangeListener, NetworkDisableFragment.CallBack {

	/* ===============================变量声明 start============================== */

	public static final String TAG = MainActivity.class.getName();

	public Context mContext;
	private Resources mResources;

	/** 退出时两次确认退出间隔时间 */
	private int CONFIRM_QUIT_TIME = 3000;
	/** 连续按两次返回键就退出 */
	private int mKeyBackCount = 0;

	/** SlidingMenu 侧滑菜单 */
	private SlidingMenu mSlidingMenu;
	private SlideMenuListAdapter mMenuListAdapter;

	/** 用户登录中心 */
	private ImageButton mUserLogin;
	/** 侧滑菜单控制面板 */
	private ListView mMenuPanelList;

	/** Actionbar的各个view */
	private LinearLayout mTitleBarLayout;
	private ImageView mMenu, mQuery, mMore;
	private TextView mTitleBarTitle;
	private PopupWindow mPopupWindow;

	/** 没有网络时的界面提示 */
	private NetworkDisableFragment mDisableFragment;

	/** 主界面的PagerSlideTab和 ViewPager */
	private PagerSlideTab mPagerTab;
	private String[] TAB_TITLES = { "店铺模式", "分类模式" };
	private ViewPager mViewPager;
	private MainPagerAdapter mMainPagerAdapter;
	private List<Fragment> mFragmentList;

	/** 退出时的效果界面 */
	private FrameLayout main_off_frameLayout;
	private ImageView main_off_imageView;

	private Handler mHandler;

	/* =========================== 变量声明 end ============================== */

	/**
	 * 主界面初始化开始
	 */
	public void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_main_layout);

		LogUtil.i(TAG, "onCreate");

		mContext = this;
		mResources = this.getResources();

		// 初始化各个UI
		initActionBar();
		initView();
		initSlidingMenu();
		initMenuList();

		// 根据网络状况显示内容
		initShow();

		mHandler = new Handler();
		mHandler.postDelayed(new Runnable() {
			public void run() {
				// 启动时检查更新
				if (AppConfigService.isStartCheckUpDate(MainActivity.this)) {
					// UpdateManager.getUpdateManager(MainActivity.this).checkUpdate(true);
				}
			}
		}, AppConfigs.APP_UPDATE_TIME);
	}

	@Override
	protected void onDestroy() {
		LogUtil.i(TAG, "onDestroy");
		super.onDestroy();
		System.exit(0);
		// android.os.Process.killProcess(android.os.Process.myPid());
	}

	@Override
	protected void onResume() {
		LogUtil.i(TAG, "onResume");
		super.onResume();
		// 重置0
		mKeyBackCount = 0;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// 按下返回键
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			switch (mKeyBackCount) {
			// 第一次按下
			case 0:
				Toast.makeText(this, R.string.press_again_exit, Toast.LENGTH_SHORT).show();
				Timer timer = new Timer();
				timer.schedule(new TimerTask() {
					public void run() {
						mKeyBackCount = 0;
					}
				}, CONFIRM_QUIT_TIME); // 3s后重新置零

				mKeyBackCount++;
				break;

			// 第二次按下
			case 1:
				main_off_frameLayout.setVisibility(View.VISIBLE);
				main_off_imageView.setVisibility(View.VISIBLE);
				Animation anim = AnimationUtils.loadAnimation(MainActivity.this, R.anim.exit_anim);
				anim.setAnimationListener(new MainOffAnimListener());
				main_off_imageView.startAnimation(anim);
				break;

			default:
				break;
			}
			return true;
		}
		// 按下了菜单键
		else if (keyCode == KeyEvent.KEYCODE_MENU) {
			if (mSlidingMenu.isMenuShowing()) {
				toggle();
			} else {
				showMenu();
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	/** 初始化SlidingMenu */
	private void initSlidingMenu() {
		setBehindContentView(R.layout.main_slidingmenu);
		mUserLogin = (ImageButton) findViewById(R.id.ib_user_login);
		mUserLogin.setOnClickListener(this);
		// 定义SlidingMenu属性
		mSlidingMenu = getSlidingMenu();
		mSlidingMenu.setMode(SlidingMenu.LEFT); // 左边侧滑方式
		// mSlidingMenu.setShadowWidth(20);
		mSlidingMenu.setShadowWidthRes(R.dimen.shadow_width); // 阴影效果宽度
		mSlidingMenu.setShadowDrawable(R.drawable.slidingmenu_shadow);// 阴影效果

		mSlidingMenu.setFadeEnabled(true);// 使用渐变效果
		mSlidingMenu.setFadeDegree(0.5f); // 设置淡入淡出效果

		mSlidingMenu.setBehindOffsetRes(R.dimen.slidingmenu_offset); // 距离右边的距离
		// mSlidingMenu.setBehindWidth(400);// slidemenu拉出的最大宽度

		mSlidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN); // 全屏触摸模式
		mSlidingMenu.setBehindScrollScale(1.0f);
	}

	/** 初始化SlideMenu上的菜单列表 */
	private void initMenuList() {
		mMenuPanelList = (ListView) findViewById(R.id.lv_behind_menu_list);
		mMenuListAdapter = new SlideMenuListAdapter(this);
		mMenuPanelList.setAdapter(mMenuListAdapter);
		// mMenuListAdapter.notifyDataSetChanged();// 改变状态了
		mMenuPanelList.setOnItemClickListener(new SlideMenuListItemListener());
	}

	/** 初始化ActionBar */
	private void initActionBar() {
		mTitleBarLayout = (LinearLayout) findViewById(R.id.linear_above_titileBar_to_menu);
		mMenu = (ImageView) findViewById(R.id.iv_above_titleBar_menu);
		mQuery = (ImageView) findViewById(R.id.iv_above_titleBar_query);
		mMore = (ImageView) findViewById(R.id.iv_above_titleBar_more);
		mTitleBarTitle = (TextView) findViewById(R.id.tv_above_titileBar_title);

		mTitleBarLayout.setOnClickListener(this);
		mMenu.setOnClickListener(this);
		mQuery.setOnClickListener(this);
		mMore.setOnClickListener(this);
		mTitleBarTitle.setText("我要下单");

		initPopupWindow();
	}

	private void initPopupWindow() {
		LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
		View layout = inflater.inflate(R.layout.main_popupwindow, null);

		ListView popupListView = (ListView) layout.findViewById(R.id.lv_popup_list);
		ArrayList<Map<String, String>> arrayList = new ArrayList<Map<String, String>>();
		Map<String, String> map;
		map = new HashMap<String, String>();
		map.put("type", "地图模式");
		arrayList.add(map);
		map = new HashMap<String, String>();
		map.put("type", "更多");
		arrayList.add(map);

		map = new HashMap<String, String>();
		map.put("type", "更更多");
		arrayList.add(map);

		SimpleAdapter adapter = new SimpleAdapter(mContext, arrayList, R.layout.main_popupwindow_item, new String[] { "type" },
				new int[] { R.id.tv_popupwindow_title });

		mPopupWindow = new PopupWindow(layout);
		// mPopupWindow = new PopupWindow(layout, LayoutParams.WRAP_CONTENT,
		// LayoutParams.WRAP_CONTENT);
		mPopupWindow.setFocusable(true);
		popupListView.setAdapter(adapter);
		// 控制popupwindow的宽度和高度自适应
		popupListView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
		mPopupWindow.setWidth(popupListView.getMeasuredWidth());
		mPopupWindow.setHeight((popupListView.getMeasuredHeight() + 10) * arrayList.size());

		mPopupWindow.setOutsideTouchable(true);
		mPopupWindow.setBackgroundDrawable(mResources.getDrawable(R.drawable.bg_popupwindow));

		popupListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				mPopupWindow.dismiss();
				switch (position) {

				case 0:
					IntentUtil.startActivity(MainActivity.this, MapMode.class);
					break;

				case 1:
					CustomToast.make(MainActivity.this).setText("更多功能升级中...").show();
					break;

				default:
					CustomToast.make(MainActivity.this).setText("更多功能升级中...").show();
					break;
				}

			}
		});
	}

	/** * 初始化一些其他View */
	private void initView() {

		main_off_frameLayout = (FrameLayout) findViewById(R.id.fl_main_off);
		main_off_imageView = (ImageView) findViewById(R.id.iv_main_off_1);
	}

	/** * Tab切换的初始化 */
	private void initPagerTab() {
		mPagerTab = (PagerSlideTab) findViewById(R.id.main_pager_slide_tab);
		// 设置其他属性
		mPagerTab.setShouldExpand(true);
		mPagerTab.setViewPager(mViewPager);
		// 添加监听滑动时间的处理,替代Viewpager.setOnPageChangeListener()
		mPagerTab.setOnPageChangeListener(this);
	}

	/** ViewPager初始化 */
	private void initViewPager() {
		initFragment();
		mViewPager = (ViewPager) findViewById(R.id.main_above_viewpager);

		mMainPagerAdapter = new MainPagerAdapter(getSupportFragmentManager(), mFragmentList, TAB_TITLES);
		mViewPager.setAdapter(mMainPagerAdapter);
	}

	private void initFragment() {
		mFragmentList = new ArrayList<Fragment>();
		mFragmentList.add(StoreMode.getInstance(null));

		mFragmentList.add(CategoryMode.getInstance(null));
	}

	/** 根据网络状况显示对应的内容 */
	private void initShow() {
		switch (AppApplication.netWorkStatus) {

		/* 没有网络 */
		case Constants.NET_TYPE_DISCONN:
			/* Falls through */
		case Constants.NET_TYPE_DISABLE:
			showNetWorkStatus(0);
			break;

		/* 网络正常 */
		case Constants.NET_TYPE_CONN:
			/* Falls through */
		case Constants.NET_TYPE_ENABLE:
			showNetWorkStatus(2);
			initViewPager();
			initPagerTab();
			break;

		default:
			break;
		}
	}

	/**
	 * 显示网络的情况界面,如果网络没开则显示设置界面,如果网络正常则显示加载的内容
	 * 
	 * @param netType
	 */
	private void showNetWorkStatus(int netType) {
		FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

		switch (netType) {
		/* 网络不正常,显示设置提示界面 */
		case Constants.NET_TYPE_DISABLE:
			mDisableFragment = NetworkDisableFragment.getInstance(null);
			transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
			transaction.replace(R.id.fl_main_show, mDisableFragment).commit();
			break;

		/* 网络正常 ,移除设置界面 */
		case Constants.NET_TYPE_CONN:
			/* Falls through */
		case Constants.NET_TYPE_ENABLE:
			if (mDisableFragment != null) {
				transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE);
				transaction.remove(mDisableFragment).commit();
			}
			break;
		default:
			break;
		}

	}

	/**
	 * 设置SlideMenu触发手势模式
	 * 
	 * @param tabPage
	 *            当前页位置
	 */
	private void setTouchMode(int tabPage) {
		if (tabPage == 0) {
			mSlidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN); // 在最前面一个时可以全屏滑动手势
		} else if (tabPage == mMainPagerAdapter.getCount() - 1) {
			// 这里只有两个tab,该写法适合多个tab/fragment的
			mSlidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN); // 到最后一个时只能使用边框来滑动,否则冲突手势
		} else {
			// 中间其他tab的处理
			mSlidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
		}
	}

	public void exit(View view) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);

		builder.setMessage("确定要退出吗?").setPositiveButton("是的", new OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				finish();
			}
		}).setNegativeButton("点错了", new OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				return;
			}
		});
		builder.show();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		// 点击了用户中心
		case R.id.ib_user_login:
			// 用户中心进入
			UIHelper.showUserInfo(MainActivity.this, Constants.LOGIN_TYPE_UCENTER);
			break;

		// 点击了菜单按钮
		case R.id.linear_above_titileBar_to_menu:
			mTitleBarTitle.setText("我要下单");
			mMenuPanelList.getChildAt(0).setSelected(true);
			mSlidingMenu.toggle(true);
			break;

		case R.id.iv_above_titleBar_menu:
			mSlidingMenu.toggle(); // 自动打开/关闭滑动菜单栏
			break;

		case R.id.iv_above_titleBar_query:
			Intent searchIntent = new Intent(MainActivity.this, SearchActivity.class);
			searchIntent.putExtra(Constants.SEARCH_TYPE, Constants.SEARCH_TYPE_STORES);
			startActivity(searchIntent);
			break;

		case R.id.iv_above_titleBar_more:
			if (mPopupWindow.isShowing()) {
				mPopupWindow.dismiss();
			} else {
				mPopupWindow.showAsDropDown(mMore);
			}
			break;

		default:
			break;
		}

	}

	@Override
	public void onPageScrollStateChanged(int arg0) {
	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {
	}

	@Override
	public void onPageSelected(int arg0) {
		// 改变Slidemenu触发方式
		setTouchMode(arg0);
	}

	/**
	 * SlideMenu List menu监听器 改变状态效果以及响应指定事件
	 */
	private class SlideMenuListItemListener implements OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			// 选中和未选中状态改变 //parent.getChildAt(position) = view
			// view.setBackgroundResource(R.drawable.bg_behind_list);
			changeSelectStatus(parent, view, position);

			// 处理点击事件
			switch (position) {

			// 我要下单
			case 0:
				// 隐藏左边菜单栏,标题栏文字相应变化
				mTitleBarTitle.setText(R.string.slidemenu_list_title_type1);
				showContent();// 显示内容
				break;

			// 我的订单
			case 1:
				UIHelper.showMyOrder(MainActivity.this, Constants.LOGIN_TYPE_MY_ORDER);
				mTitleBarTitle.setText(R.string.slidemenu_list_title_type2);
				break;

			// 我的评价
			case 2:
				UIHelper.showMyComment(MainActivity.this, Constants.LOGIN_TYPE_MY_COMMENT);
				mTitleBarTitle.setText(R.string.slidemenu_list_title_type3);
				break;

			// 系统设置
			case 3:
				IntentUtil.startActivity(MainActivity.this, SettingActivity.class);
				mTitleBarTitle.setText(R.string.slidemenu_list_title_type4);
				break;

			// 关于我们
			case 4:
				IntentUtil.startActivity(MainActivity.this, AboutApp.class);
				mTitleBarTitle.setText(R.string.slidemenu_list_title_type5);
				break;

			default:
				break;
			}
		}

		/**
		 * SlideMenu 列表 改变选中的状态,选中时背景色改变
		 * 
		 * @param parent
		 * @param view
		 * @param position
		 */
		public void changeSelectStatus(AdapterView<?> parent, View view, int position) {
			for (int i = 0; i < parent.getChildCount(); i++) {
				parent.getChildAt(i).setBackgroundColor(Color.TRANSPARENT); // 全部为透明
				((TextView) (parent.getChildAt(i).findViewById(R.id.tv_menu_list_line_title))).setTextColor(mResources
						.getColor(R.color.defaultTextColor));
			}
			parent.getChildAt(position).setBackgroundResource(R.drawable.bg_behind_list); // 选中当前
			((TextView) (parent.getChildAt(position).findViewById(R.id.tv_menu_list_line_title))).setTextColor(mResources.getColor(R.color.black));
		}
	}

	/** 网络设置 */
	public void setNetWork(Context context) {
		UIHelper.showNetWorkSetup(this);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
		super.onActivityResult(requestCode, requestCode, intent);
		switch (requestCode) {
		case Constants.SETUP_NETWORK_REQUEST_CODE:
			// 网络状态改变了
			if (resultCode == Constants.SETUP_NETWORK_RESULT_CODE) {
				initShow();
			}
			break;

		default:
			break;
		}
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		LogUtil.i(TAG, "onSaveInstanceState");

		AppApplication app = (AppApplication) getApplication();
		if (app.isLogin()) {
			((TextView) findViewById(R.id.tv_slide_menu_uc_username)).setText(app.getLoginUser().getName());
			((ImageView) findViewById(R.id.iv_slide_menu_uc_head)).setVisibility(View.VISIBLE);
			((ImageView) findViewById(R.id.iv_slide_menu_uc_status)).setVisibility(View.VISIBLE);
		}
	}

	// 退出动画监听器
	private class MainOffAnimListener implements AnimationListener {

		@Override
		public void onAnimationEnd(Animation animation) {

			defaultFinish();
		}

		@Override
		public void onAnimationRepeat(Animation animation) {

		}

		@Override
		public void onAnimationStart(Animation animation) {

		}

	}

}
